//
//  musicManager.m
//  B项目
//
//  Created by lanou on 16/8/9.
//  Copyright © 2016年 Work. All rights reserved.
//

#import "musicManager.h"
#import "musicModel.h"
#import "PrefixHeader.pch"

static musicManager *_manager = nil;
@implementation musicManager

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[musicManager alloc]init];

    });

    [[NSNotificationCenter defaultCenter]addObserver:_manager selector:@selector(playNextSong) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

    return _manager;
}

- (instancetype)init
{
    if (self = [super init]) {
        _player = [[AVPlayer alloc]init];
    }

    return self;
}

//解析
- (void)loadSongInfo
{
    musicModel *model = self.musicArray[_index];
    NSString *urlStringOne = @"http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.getInfos&ts=1445484488&songid=";
    NSString *urlStringTwo = @"&nw=2&l2p=0&lpb=0&ext=mp3&format=json&from=ios&usup=1&lebo=0&aac=0&ucf=4&vid=&res=1&e=USbMxKUnchkbhCYmky%2B5RJ%2FpxskZMYC1wjYkv8AHsvo%3D&version=5.3.2&from=ios&channel=appstore";
    NSString *urlString = [NSString stringWithFormat:@"%@%@%@",urlStringOne,model.song_id,urlStringTwo];


    
    [NetWorkRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {


        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dict[@"songurl"][@"url"];
        self.model = [[PlayerModel alloc]init];
        [self.model setValuesForKeysWithDictionary:array[0]];
        [self.model setValuesForKeysWithDictionary:dict[@"songinfo"]];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"loadData" object:nil];
        [self playMusic:self.model.file_link];



    } finishError:^(NSError *error) {
        NSLog(@"+++++++++++%@",error);

    }];


}


- (void)playMusic:(NSString *) fileLink
{
    if (self.playerItem != nil) {
        [self.playerItem removeObserver:self forKeyPath:@"status"];
    }
    self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:fileLink]];
    [self.playerItem addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld) context:nil];
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    switch ([change[@"new"] integerValue]) {
        case AVPlayerItemStatusFailed:
            NSLog(@"歌曲缓冲失败");
            break;
        case AVPlayerItemStatusReadyToPlay:
            self.readToPlay = YES;
            [self startPlayMusic];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"readToPlay" object:nil];
             break;
        case AVPlayerStatusUnknown:
            NSLog(@"缓冲状态未知");
            break;

        default:
            NSLog(@"default");
            break;
    }
}


//开始播放
- (void)startPlayMusic
{
    if (self.readToPlay == YES) {
        [_player play];
    }

}

//暂停
- (void)pauseMusic
{
    [_player pause];
    _readToPlay = NO;
}

//暂停/播放
- (void)playOrPause
{
    if (self.readToPlay == YES) {
        [self startPlayMusic];
    }else{
        [self startPlayMusic];
    }

}

//上一首
- (void)playerAbover
{
    if (self.index == 0) {
        self.index = self.musicArray.count - 1;
    }else{
        self.index = self.index - 1;
    }

    [self loadSongInfo];

}

//下一首
- (void)playerNext
{
    if (self.index == self.musicArray.count - 1) {
        self.index = 0;
    }else{
        _index = _index + 1;
    }
    [self loadSongInfo];

}


//播放模式

- (void)playNextSong
{
    switch (self.playStyle) {
        case 0:
            [self playRound];
            break;
        case 1:
            [self playSingle];
            break;
        case 2:
            [self playRandom];
            break;
        case 3:
            [self playOrder];
            break;

        default:
            NSLog(@"unkonw");
            break;
    }
}

//单曲循环
- (void)playSingle
{
    [self playMusic:self.model.file_link];

}
//循环播放
- (void)playRound
{
    self.index = _index = self.musicArray.count -1 ? 0 : _index+1 ;
    [self loadSongInfo];

}
//顺序播放
- (void)playOrder
{
    if (_index == self.musicArray.count - 1) {
        [self.player pause];
    }else{
        _index ++;
        [self loadSongInfo];
    }

}
//随机播放
- (void)playRandom
{
    NSInteger tempIndex = arc4random_uniform((u_int32_t)(self.musicArray.count));
    _index = tempIndex;
    [self loadSongInfo];

}

//播放进度
- (void)playerProgressWithProgressFloat:(CGFloat)progressFloat
{
    [self.player seekToTime:CMTimeMakeWithSeconds(progressFloat, 1) completionHandler:^(BOOL finished) {
        [self startPlayMusic];
    }];

}

@end
